import {TaskStatus} from "../models/task.ts";

const KB = 1024;
const MB = 1024*KB;
const GB = 1024*MB;



const hashCode = (str:string):number => {
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
        const char = str.charCodeAt(i);
        hash = ((hash << 5) - hash) + char; // hash * 31 + char
        hash |= 0; // 转换为 32 位整数
    }
    return hash;
}

/**
 * 格式化 FileSize
 * @param fileSize
 */
const formatSize = (fileSize:number):string =>{
    if (fileSize<=MB){
        return (fileSize / KB).toFixed(0)+" KB";
    }
    if (fileSize<=GB) {
        return (fileSize / MB).toFixed(1)+" MB";
    }
    return (fileSize / GB).toFixed(1)+" GB";
}


/**
 * 计算dir的size
 * @param entry
 * @param path
 */
 async function getDirOrFileSize(entry: FileSystemEntry, path = '') {
    let totalSize = 0;

    if (entry.isFile) {
        // console.debug('File:', path + entry.name);

        const file: File = await new Promise((resolve, reject) => {
            (entry as FileSystemFileEntry).file((file) => resolve(file), reject);
        });
        totalSize += file.size;

    } else if (entry.isDirectory) {
        // console.debug('Folder:', path + entry.name);

        const dirReader = (entry as FileSystemDirectoryEntry).createReader();

        const entries: FileSystemEntry[] = await new Promise((resolve, reject) => {
            dirReader.readEntries((entries) => resolve(entries), reject);
        });

        for (let subEntry of entries) {
            totalSize += await getDirOrFileSize(subEntry, path + entry.name + '/');
        }
    }
    return totalSize;
}


function formatStatus(status: TaskStatus):string{
     switch (status){
         case TaskStatus.CREATED:
             return "未开始";
         case TaskStatus.RUNNING:
             return "传输中";
         case TaskStatus.SUSPEND:
             return "已暂停";
         case TaskStatus.CANCEL:
             return "已取消";
         case TaskStatus.COMPLETE:
             return "已完成";
         default:
             return "---";
     }
}
 export  {
     getDirOrFileSize,
     formatSize,
     hashCode,
     formatStatus,
 }